var fs = require('fs')
const Sequelize = require('sequelize')
const { like, or, in: opIn } = Sequelize.Op
const { BooksModel } = require('./dao/model.js')
const { UserModel } = require('./dao/model.js')

const BooksService = {
  //书籍上传
  bookupload(req, res, next) {
    const {
      bookname,
      author,
      bookversion,
      bookpress,
      bookDescribe,
      booksimgs,
      tag,
      classify,
      userId
    } = req.body

    //将本书存入数据库
    const bookId = new Date().getTime()
    BooksModel.create({
      bookId,
      bookName: bookname,
      author: author,
      bookVersion: bookversion,
      bookPress: bookpress,
      bookDescribe: bookDescribe,
      tags: tag,
      classify: classify,
      userId: userId
    }).then(data => {
      const base64Data = booksimgs[0].thumbUrl.replace(
        /^data:image\/\w+;base64,/,
        ''
      )
      const avatarBuffer = Buffer.from(base64Data, 'base64')
      fs.writeFile(
        `./src/assets/booksImages/${bookId}.jpg`,
        avatarBuffer,
        function(err) {
          if (err) {
            console.log(err)
            console.log('保存失败')
          } else {
            console.log('保存成功')
          }
        }
      )
      UserModel.findAll({
        where: {
          userId
        }
      }).then(data => {
        //上传者的列表中加入本书id
        const mybooksList = data[0].mybooks ? data[0].mybooks.split(',') : []
        mybooksList.push(bookId)
        const newmybooks = { mybooks: `${mybooksList.toString()}` }
        UserModel.update(newmybooks, {
          where: { userid: userId }
        })
      })
      res.json({
        res_code: 200,
        res_error: '',
        data: {
          messagge: 'success',
          status: 1,
          data
        }
      })
    })
  },
  //书籍收藏
  bookcollect(req, res, next) {
    const { bookId, userId } = req.body
    BooksModel.findAll({
      where: {
        bookId
      }
    }).then(data => {
      const newCollectNum = { collectNum: data[0].collectNum + 1 }
      BooksModel.update(newCollectNum, {
        where: {
          bookId
        }
      })
    })
    UserModel.findAll({
      where: {
        userId
      }
    }).then(data => {
      const collectList = data[0].collect ? data[0].collect.split(',') : []
      collectList.push(bookId)
      const newcollect = { collect: `${collectList.toString()}` }
      UserModel.update(newcollect, {
        where: { userid: userId }
      }).then(data => {
        res.json({
          res_code: 200,
          res_error: '',
          data: {
            messagge: 'success',
            status: 1,
            data: collectList
          }
        })
      })
    })
  },
  //取消收藏
  bookcancelcollect(req, res, next) {
    const { bookId, userId } = req.body
    UserModel.findAll({
      where: {
        userId
      }
    }).then(data => {
      const newCollectList = data[0].collect
        .split(',')
        .filter(value => value !== bookId)
      const newcollect = { collect: `${newCollectList.toString()}` }
      UserModel.update(newcollect, {
        where: { userid: userId }
      }).then(data => {
        res.json({
          res_code: 200,
          res_error: '',
          data: {
            messagge: 'success',
            status: 1,
            collect: newCollectList.toString()
          }
        })
      })
    })
  },
  //书籍借阅
  bookborrow(req, res, next) {
    const { bookId, userId } = req.body
    //更新本用户借阅书籍列表
    UserModel.findAll({
      where: {
        userId
      }
    }).then(data => {
      const borrowList = data[0].borrow ? data[0].borrow.split(',') : []
      borrowList.push(bookId)
      const newborrow = { borrow: `${borrowList.toString()}` }
      UserModel.update(newborrow, {
        where: { userid: userId }
      }).then(data => {
        //更新本书库存
        BooksModel.findAll({
          where: {
            bookId
          }
        })
          .then(data => {
            const newinventory = { inventory: data[0].inventory - 1 }
            BooksModel.update(newinventory, {
              where: { bookId }
            })
          })
          .then(data => {
            res.json({
              res_code: 200,
              res_error: '',
              data: {
                messagge: 'success',
                status: 1,
                borrow: borrowList.toString()
              }
            })
          })
      })
    })
  },
  //书籍归还
  bookcancelborrow(req, res, next) {
    const { bookId, userId } = req.body
    //更新本用户借阅书籍列表
    UserModel.findAll({
      where: {
        userId
      }
    }).then(data => {
      const borrowList = data[0].borrow
        .split(',')
        .filter(value => value !== bookId)
      const newborrow = { borrow: `${borrowList.toString()}` }
      UserModel.update(newborrow, {
        where: { userid: userId }
      }).then(data => {
        //更新本书库存
        BooksModel.findAll({
          where: {
            bookId
          }
        })
          .then(data => {
            const newinventory = { inventory: data[0].inventory + 1 }
            BooksModel.update(newinventory, {
              where: { bookId }
            })
          })
          .then(data => {
            res.json({
              res_code: 200,
              res_error: '',
              data: {
                messagge: 'success',
                status: 1,
                borrow: borrowList.toString()
              }
            })
          })
      })
    })
  },
  //书籍删除
  bookdelete(req, res, next) {
    const { bookId, userId } = req.body
    BooksModel.destroy({
      where: {
        bookId
      }
    }).then(data => {
      fs.unlinkSync(`./src/assets/booksImages/${bookId}.jpg`)
      UserModel.findAll({
        where: {
          userId
        }
      }).then(data => {
        const newMybooksList = data[0].mybooks
          .split(',')
          .filter(value => value !== bookId)
        const newmybooks = { mybooks: `${newMybooksList.toString()}` }
        UserModel.update(newmybooks, {
          where: { userid: userId }
        }).then(data => {
          res.json({
            res_code: 200,
            res_error: '',
            data: {
              messagge: 'success',
              status: 1,
              mybooks: newMybooksList.toString()
            }
          })
        })
      })
    })
  },
  //获取书籍
  bookslist(req, res, next) {
    const {
      bookid,
      classify,
      tags,
      uploadDate,
      collectNum,
      keyWords,
      status
    } = req.body
    //通过关键字查询
    if (keyWords) {
      BooksModel.findAll({
        where: {
          [or]: [
            {
              bookName: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              author: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              bookVersion: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              bookPress: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              bookDescribe: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              tags: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              classify: {
                [like]: '%' + keyWords + '%'
              }
            }
          ],
          status: 'allow'
        }
      }).then(data => {
        res.json({
          res_code: 200,
          res_error: '',
          data: {
            messagge: 'success',
            status: 1,
            data
          }
        })
      })
    }
    //分类型搜索
    if (classify || tags || uploadDate || collectNum) {
      BooksModel.findAll({
        where: {
          classify: classify,
          status: 'allow'
        }
      }).then(data => {
        res.json({
          res_code: 200,
          res_error: '',
          data: {
            messagge: 'success',
            status: 1,
            data
          }
        })
      })
    } else {
      BooksModel.findAll({
        where: {
          status: 'allow'
        }
      }).then(data => {
        res.json({
          res_code: 200,
          res_error: '',
          data: {
            messagge: 'success',
            status: 1,
            data
          }
        })
      })
    }
  },
  //获取我的书籍列表
  mybookslist(req, res, next) {
    const { bookid } = req.body
    const newbookid = bookid === null ? [] : bookid.split(',')
    BooksModel.findAll({
      where: {
        bookId: {
          [opIn]: newbookid
        }
      }
    }).then(data => {
      res.json({
        res_code: 200,
        res_error: '',
        data: {
          messagge: 'success',
          status: 1,
          data
        }
      })
    })
  },
  //获取管理书籍列表
  adminbookslist(req, res, next) {
    const { status, keyWords } = req.body
    if (keyWords) {
      BooksModel.findAll({
        where: {
          [or]: [
            {
              bookName: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              author: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              bookVersion: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              bookPress: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              bookDescribe: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              tags: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              classify: {
                [like]: '%' + keyWords + '%'
              }
            },
            {
              userDescribe: {
                [like]: '%' + keyWords + '%'
              }
            }
          ],
          status
        }
      }).then(data => {
        res.json({
          res_code: 200,
          res_error: '',
          data: {
            messagge: 'success',
            status: 1,
            data
          }
        })
      })
    } else {
      BooksModel.findAll({
        where: {
          status
        }
      }).then(data => {
        res.json({
          res_code: 200,
          res_error: '',
          data: {
            messagge: 'success',
            status: 1,
            data
          }
        })
      })
    }
  },
  //管理书籍状态
  adminbooks(req, res, next) {
    const { bookId, status, nowStatus } = req.body
    const nesBooksStatus = { status }
    BooksModel.update(nesBooksStatus, {
      where: { bookId }
    }).then(data => {
      BooksModel.findAll({
        where: { status: nowStatus }
      }).then(data => {
        res.json({
          res_code: 200,
          res_error: '',
          data: {
            messagge: 'success',
            status: 1,
            data
          }
        })
      })
    })
  }
}
module.exports = BooksService
